/******************************************************************************
 * File: : Roomplan.cpp
 * Autor : Thomas Pfeiffer
 * Descr.: Implementation of the class Roomplan
 *****************************************************************************/
#include "Roomplan.h"
#include "Side.h"
#include "Door.h"

// Add a new room to the list. (The room is being copied)
// Returns an index which can be used to access the room later
size_t Roomplan::addRoom( Room const & newroom )
{
	size_t rnr = mRooms.size();  // determine the next room index
	mRooms.push_back(newroom);   // add a copy of the room to the list
  
  // tell the room its index and dimension
	mRooms.back().setIndex(rnr);
	mRooms.back().setDimension(mWidth, mHeight);
  
	return rnr;  // return the room index
}

// Connects the room with the index "index" to the room
// with the next index. If there is no next index, it does nothing
void Roomplan::connectToNext( size_t index )
{
  // do nothing if the roomindex is invalid ( i < 0 or i >= lastroomindex)
	if (index >= 0 && index < (mRooms.size() - 1)) {
    // get pointers to the rooms that should be connected
		Room * firstroom = getRoom(index);
		Room * nextroom  = getRoom(index + 1);

		size_t len = firstroom->getBottom()->getLength();  // get the length of a side

    // Add a new side to the room and set its neighbour
		firstroom->setBottom(new Door(len));  // the set.. function frees the old side ( delete mBottom)
		firstroom->getBottom()->setNeighbour(nextroom);
		
    // Add a new side to the room and set its neighbour
		nextroom->setTop(new Door(len));    // the set.. function frees the old side (delete mTop)
		nextroom->getTop()->setNeighbour(firstroom);
	}
}

// Print all of the rooms in the list
void Roomplan::Print() const
{
  // For every room in the list, call the print function
  // The parameter false tells the room that it shouldn't print the
  // top side if it has a neighbour
	for (TRoomConstIterator it = mRooms.begin(); it != mRooms.end(); ++it) {
		it->Print(false);
	}
}

// Return a previously added room. The room is specified by
// the index returned by addRoom
Room* Roomplan::getRoom( size_t index )
{
	TRoomIterator it = mRooms.begin();
	for (size_t i = 0; i < index; ++i) {
		++it;
	}
	return &(*it);
}